from django.shortcuts import render
from books.models import HeroInfo
from heros.serialziers import HeroSerializer
import json
from rest_framework.views import APIView
from rest_framework.response import Response

# Create your views here.
class HerosView(APIView):

    def get(self, request):
        """
            获取所有英雄
        :param request:
        :return:
        """
        # 查询所有英雄
        heros = HeroInfo.objects.all()
        # 构造返回数据
        ser = HeroSerializer(heros, many=True)
        return Response(ser.data)

    def post(self, request):
        """
            保存英雄
        :param request:
        :return:
        """
        # 获取数据 request.data获取的json是转化后的字典数据
        data_dict = request.data
        # 验证数据
        ser = HeroSerializer(data=data_dict)
        try:
            ser.is_valid(raise_exception=True)
        except:
            return Response({'errors': ser.errors}, status=400)
        # 保存数据
        ser.save()
        # 返回结果
        return Response(ser.data)


class HeroView(APIView):

    def get(self, request, pk):
        try:
            hero = HeroInfo.objects.get(id=pk)
        except:
            return Response({'error': '数据不存在'}, status=400)

        ser = HeroSerializer(hero)
        return Response(ser.data)

    def put(self, request, pk):
        try:
            hero = HeroInfo.objects.get(id=pk)
        except:
            return Response({'error': '数据不存在'}, status=400)
        # 转化字典
        data_dict = request.data
        ser = HeroSerializer(hero, data=data_dict)
        try:
            ser.is_valid(raise_exception=True)
        except:
            return Response({'errors': ser.errors}, status=400)
        # 更新
        ser.save()
        return Response(ser.data)

    def delete(self, request, pk):
        try:
            hero = HeroInfo.objects.get(id=pk)
        except:
            return Response({'error': '数据不存在'}, status=400)

        hero.is_delete = True
        hero.save()
        return Response({})
